/*
 * Copyright (c) 2012 Google Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

package com.coms514.scheduleme;

import com.google.api.client.googleapis.extensions.android.gms.auth.GooglePlayServicesAvailabilityIOException;
import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException;
import com.google.api.services.calendar.model.CalendarList;
import com.google.api.services.calendar.model.CalendarListEntry;

import android.os.AsyncTask;
import android.util.Log;
import android.view.View;

import java.io.IOException;
import java.util.ArrayList;

/**
 * Asynchronous task that also takes care of common needs, such as displaying progress,
 * authorization, exception handling, and notifying UI when operation succeeded.
 * 
 * @author Yaniv Inbar
 */
class CalendarListAsyncTask extends AsyncTask<Void, Void, Boolean> {
	final String TAG = "CalendarListAsyncTask";
	
	final Feedback2Activity activity;
	final com.google.api.services.calendar.Calendar client;
	final ArrayList<CalendarListItem> calendarList;
	private final View progressBar;
	
	CalendarListAsyncTask(Feedback2Activity activity) {
		this.activity = activity;
		calendarList = activity.calendarList;
		client = activity.client;
		progressBar = activity.findViewById(R.id.title_refresh_progress);
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		activity.numAsyncTasks++;
		progressBar.setVisibility(View.VISIBLE);
	}

	@Override
	protected final Boolean doInBackground(Void... ignored) {
		try {
			doInBackground();
			return true;
		} catch (final GooglePlayServicesAvailabilityIOException availabilityException) {
			
			println("GooglePlayServicesAvailabilityIOException");
			
			activity.showGooglePlayServicesAvailabilityErrorDialog(
					availabilityException.getConnectionStatusCode());
		} catch (UserRecoverableAuthIOException userRecoverableException) {
			
			println("userRecoverableException");
			
			activity.startActivityForResult(
					userRecoverableException.getIntent(), Feedback2Activity.REQUEST_AUTHORIZATION);
		} catch (IOException e) {
			
			println(e.toString());
			
			Utils.logAndShow(activity, Feedback2Activity.TAG, e);
		}
		return false;
	}

	@Override
	protected final void onPostExecute(Boolean success) {
		super.onPostExecute(success);
		if (0 == --activity.numAsyncTasks) {
			progressBar.setVisibility(View.GONE);
		}
		if (success) {
			activity.displayData();
		}
	}

	protected void doInBackground() throws IOException {
		CalendarList feed = client.calendarList().list().setFields(CalendarInfo.FEED_FIELDS).execute();
		for (CalendarListEntry calendar : feed.getItems()) {
			println("calendar: " + calendar.getSummary());
			calendarList.add(new CalendarListItem(calendar.getSummary(), false));
		}
	}
	
	static void run(Feedback2Activity feedback2Activity) {
		new CalendarListAsyncTask(feedback2Activity).execute();
	}
	
	/* for logging */
	private void println(String msg) {
		Log.d(TAG, msg);
	}
}
